//
//  QRCodeViewController.swift
//  WeiBo
//
//  Created by Gao on 16/3/6.
//  Copyright © 2016年 Gao. All rights reserved.
//

import UIKit
import AVFoundation
/// 二维码控制器
class QRCodeViewController: UIViewController,UITabBarDelegate
{
    /// 底部工具条
    @IBOutlet weak var myTabBar: UITabBar!
    
    @IBAction func close(sender: UIBarButtonItem)
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //冲击波的顶部间距
    @IBOutlet weak var scanLineTopCons: NSLayoutConstraint!
    //冲击波视图
    @IBOutlet weak var scanLineView: UIImageView!
    //扫描界面整体的高度
    @IBOutlet weak var scanViewTotalHeight: NSLayoutConstraint!
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        myTabBar.selectedItem = myTabBar.items![0]
        myTabBar.delegate = self
    }
    
    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated)
        
        startAnimation()
        //开始扫描
        startScan()
    }
    
    func startAnimation()
    {
        //1.初始化位置
        self.scanLineTopCons.constant = -self.scanViewTotalHeight.constant
        self.scanLineView.layoutIfNeeded()
        
        UIView.animateWithDuration(2.0, animations:
        {
            () -> Void in
            //2.结束位置
            self.scanLineTopCons.constant = 5
            //3.重复次数
            UIView.setAnimationRepeatCount(MAXFLOAT)
            //4.更新界面
            self.scanLineView.layoutIfNeeded()
            }, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: -UITabBarDelegate
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem)
    {
        //1.移除动画
        self.scanLineView.layer.removeAllAnimations()
        //2.更改高度
        if item.title == "二维码"
        {
            self.scanViewTotalHeight.constant = 300
        }
        else
        {
            self.scanViewTotalHeight.constant = self.scanViewTotalHeight.constant * 0.5
        }
        //3.重新开始动画
        startAnimation()
    }
    
    //MARK: -扫描的相关处理
    
    //1.创建会话
    lazy var session:AVCaptureSession = AVCaptureSession()
    
    //2.输入设备
    lazy var deviceInput:AVCaptureDeviceInput? =
    {
        //照相机
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do
        {
            let input = try AVCaptureDeviceInput(device: device)
            return input
        }
        catch
        {
            print(error)
            return nil
        }
    }()
    //3.输出对象
    lazy var output:AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    //4.预览图层
    lazy var PreviewLayer:AVCaptureVideoPreviewLayer =
    {
        //摄像头捕获到的界面数据 存在了session中
        let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()
    
    //5.辅助图层（二维码附近的框）
    lazy var cornerLayer:CALayer =
    {
        let layer = CALayer()
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()
    
    func startScan()
    {
       //1.是否能将输入添加到会话中
        if !session.canAddInput(deviceInput)
        {
            return
        }
       //2.是否能将输出添加到会话中
        if !session.canAddOutput(output)
        {
            return
        }
        
        //1和2因为模拟器没有摄像头 拿不到输入设备，需要判断
        
        //3.添加输入和输出到设备中
        session.addInput(deviceInput)
        session.addOutput(output)
        
        //4.能够解析的数据类型
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        //5.设置输出对象的代理 进行对数据的处理
        output.setMetadataObjectsDelegate(self, queue:dispatch_get_main_queue())
        //6.添加预览图层(不添加后面白茫茫一片)
        view.layer.insertSublayer(PreviewLayer, atIndex: 0)
        //7.添加辅助框
        PreviewLayer.addSublayer(cornerLayer)
        //8.开始扫描
        session.startRunning()
    }
   
}
//MARK -AVCaptureMetadataOutputObjectsDelegate
extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate
{
    
    //扫描到数据会调用这个方法
     func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!)
     {
        //清空辅助框内的图层
        clearCornerLayer()
        // metadataObjects 里面的实例都是AVMetadataObject 这个抽象类 转换成子类 AVMetadataMachineReadableCodeObject
        for object in metadataObjects
        {
            if object is AVMetadataMachineReadableCodeObject
            {
                let CornerObject = PreviewLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
                drawCorners(CornerObject)
            }
        }
    }
    
    func drawCorners(CornerObject:AVMetadataMachineReadableCodeObject)
    {
        if CornerObject.corners.isEmpty
        {
            return;
        }
        
        //1.设置图层
        let layer = CAShapeLayer()
            layer.strokeColor = UIColor.greenColor().CGColor
            layer.fillColor = UIColor.clearColor().CGColor
            layer.lineWidth = 5.0
        
        //2.创建路径
        let path = UIBezierPath()
        var point = CGPointZero
        var index = 0
        
        //2.1移动到第一个点
        //从corner数组中取出第一个点，赋值到point
        CGPointMakeWithDictionaryRepresentation(CornerObject.corners[index++] as! CFDictionaryRef, &point)
        path.moveToPoint(point)
        while (index < CornerObject.corners.count)
        {
            CGPointMakeWithDictionaryRepresentation(CornerObject.corners[index++] as! CFDictionaryRef, &point)
            path.addLineToPoint(point)
        }
        //3.关闭路径
        path.closePath()
        
        //4.绘制路径
        layer.path = path.CGPath
        
        //5.绘制到辅助视图
        cornerLayer.addSublayer(layer)
    }
    
    func clearCornerLayer()
    {
        if cornerLayer.sublayers == nil || cornerLayer.sublayers?.count == 0
        {
            return ;
        }
        
        for sublayer in cornerLayer.sublayers!
        {
            sublayer.removeFromSuperlayer()
        }
    }
}
